package com.adee.java.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@MyTargetType(value = "注解测试类", id = 1)
public class AnnotationTest {
    @MyTargetField(value = "字段name，表示人名", id = 5)
    private String name;
    @MyTargetMethod(value = "方法hello，用于问候", id = 6)
    public String hello(@MyTargetParameter String greetings) {
        return name + ", " + greetings;
    }
    public static void main(String[] args) {
        MyTargetType tp = AnnotationTest.class.getAnnotation(MyTargetType.class);
        System.out.println("类上的注解值value=" + tp.value() + ", id=" + tp.id());
        MyTargetMethod tm;
        try {
            Method hello = AnnotationTest.class.getDeclaredMethod("hello", String.class);
            tm = hello.getAnnotation(MyTargetMethod.class);
            System.out.println("方法hello上的注解值value=" + tm.value() + ", id=" + tm.id());
            // 获取方法上的所有参数注解，循环所有注解找到MyTargetParameter注解
            Annotation[][] annotations = hello.getParameterAnnotations();
            for(Annotation[] tt : annotations) {
                for(Annotation t : tt) {
                    if(t instanceof MyTargetParameter) {
                        System.out.println("hello方法参数注解值value=" + ((MyTargetParameter) t).value());
                    }
                }
            }
            hello.invoke(new AnnotationTest(), "修改hello方法的默认参数");
            MyTargetField fa = AnnotationTest.class.getDeclaredField("name").getAnnotation(MyTargetField.class);
            System.out.println("字段name上的注解值value=" + fa.value() + ", id=" + fa.id());

        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}
